package com.bpzj.web.spring.file;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;


@RestController
@Slf4j
public class GetFileResource {

  private static final String imgPath = "D:\\钓鱼.jpg";

  @GetMapping("/img/url")
  public void urlShowPicture(@RequestParam("url") String url, @RequestParam("token") String token, HttpServletResponse response) {
    log.info("imgPath: {}", imgPath);
    log.info("url: {}", url);
    log.info("token: {}", token);

    Path path = Paths.get(imgPath);
    String name = path.getFileName().toString();

    try {
      name = URLEncoder.encode(name, "utf-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    // 学习 BufferedOutputStream 和 FileOutputStream 的区别
    try (
        InputStream inputStream = new FileInputStream(path.toFile());
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
    ) {
      response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
      response.setHeader("Content-Disposition", "attachment; filename=" + name);
      response.setHeader("Cache-Control", "public");
      // response.setHeader("Last-Modified", DateTimeUtil.getCurrentDateTime());
      response.setCharacterEncoding("UTF-8");

      // todo 完善文件读取
      byte[] buff = new byte[2048];
      int byresRead = 0;
      // 记录文件大小
      int count = 0;
      while (-1 != (byresRead = bis.read(buff, 0, buff.length))) {
        outputStream.write(buff, 0, byresRead);
        count += byresRead;
      }
      // 文件大小
      response.setContentLength(count);
      outputStream.flush();

    } catch (IOException e) {
      log.info(e.getMessage());
    }

  }

}
